package com.newlink.building.secret.ui

import android.content.ContentValues
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_DoorKeyRepeatType
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.SecretKeyData
import com.newlink.building.common_base.model.bean.SecretKeyDeleteRequest
import com.newlink.building.common_base.model.bean.SecretKeyInfoRequest
import com.newlink.building.common_base.model.bean.StatusData
import com.newlink.building.common_base.utils.Base_DensityUtil
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.QRCodeUtils
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.secret.R
import com.newlink.building.secret.databinding.ActivityShareSecretkeyBinding
import com.newlink.building.secret.fragment.Module_Secret_TempSecretFragment
import com.newlink.building.secret.mvp.contract.Module_Secret_SecretKeyContract
import com.newlink.building.secret.mvp.presenter.Module_Secret_SecretKeyPresenter
import com.newlink.building.secret.utils.Module_Secret_BitmapUtils
import com.newlink.building.secret.utils.Module_Secret_CryptoHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.backgroundColor
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date


/**
 * Created by xiaodong on 2022/9/26.
 */
class Module_Secret_SecretKeyDetailActivityNL :
    NL_BaseMvpActivity<Module_Secret_SecretKeyContract.View, Module_Secret_SecretKeyContract.Presenter>(),
    Module_Secret_SecretKeyContract.View, View.OnClickListener {
    private val QR_IMAGE_SIZE: Int = 227
    private val fileName = "screenshot.png"
    private var isPreview: Boolean = false
    private var leftIcon: ImageView? = null
    private var rightIcon: ImageView? = null
    private var centerTitle: TextView? = null
    private var leftTitle: TextView? = null
    private var backLayout: LinearLayout? = null
    private var secretKeyId: String = ""
    private var deviceMac: String = ""
    private val REQUEST_SAVE_PICTURE_CODE: Int = 10001
    private val GEN_KEY = "4CADB82095639211A1403639D91E9150"

    override fun allowFontScale() = false

    override fun refreshSecretKeyInfo(data: SecretKeyData) {
        mBinding.keyNameValue.text = data.name
        mBinding.keyCodeValue.text = data.tmpPwd
        mBinding.keyCodeCenter.text =
            getString(R.string.secretkey_detail_opendoor_code).plus(data.tmpPwd)
        if (data.tmpPwd != null) {
            //AES加密成设备识别的开门码
            val encryptedPwd: String? = Module_Secret_CryptoHandler.encryptBase64String(GEN_KEY, data.tmpPwd!!)

            /**
             * 需要添加头部
             * CIFI-A://表示信息文本未压缩的加密文本解密前无需解压缩
             * CIFI-Z://表示信息文本为压缩文本，解密前需要先解压缩
             */
            val displayPwd = "CIFI-A://$encryptedPwd"
            NLog.e("SecretKeyDetailActivity tmpPwd:${data.tmpPwd} displayPwd: $displayPwd")
            refreshQRCode(displayPwd)
        }

        //存在服务器删除设备的情况,提示用户无效
        if (data.devices == null) {
            showToast(getString(R.string.secretkey_error_no_device))
            mBinding.keyOpennumValue.text = "0"
        } else {
            //目前一个码仅针对一个设备
            if (data.devices.size == 1) {
                mBinding.keyDevices.text = data.devices[0].name
                mBinding.keyOpennumValue.text =
                    if (data.devices[0].openNum == -1) getString(R.string.secretkey_frequency_infinite) else data.devices[0].openNum.toString()
            }
            //目前一个码可针对多个设备
            if (data.devices.size > 0) {
                val nameBuilder = StringBuilder()
                val openNumBuild = StringBuilder()
                //多个设备名称和开门次数先用符号隔开
                for (item in data.devices) {
                    nameBuilder.append(item.name).append("/")
                    openNumBuild.append(item.openNum).append("/")
                }
                nameBuilder.deleteCharAt(nameBuilder.length - 1)
                openNumBuild.deleteCharAt(openNumBuild.length - 1)
                mBinding.keyDevices.text = nameBuilder.toString()
                mBinding.keyOpennumValue.text =
                    if (data.devices[0].openNum == -1) getString(R.string.secretkey_frequency_infinite) else openNumBuild.toString()
            }
        }

        val repeatType = data.repeatType
        val effectTime = data.effectTime?.toTypedArray()?.joinToString(File.separator)
        val periodArray = resources.getStringArray(R.array.secretkey_array_repetition_period)
        var repeatDisplay = ""

        if (repeatType in 1..periodArray.size) {
            var periodDisplay = periodArray[repeatType - 1]
            repeatDisplay = when (repeatType) {
                //重复为每周时, 0对应星期日
                Base_DoorKeyRepeatType.WEEKLY.type -> "$periodDisplay(${effectTime?.replace("0", "7")})"
                Base_DoorKeyRepeatType.MONTHLY.type -> "$periodDisplay($effectTime)"
                else -> periodDisplay
            }
        }
        mBinding.keyRepeatValue.text = repeatDisplay

        val periodStr = data.period.orEmpty()
        if (periodStr.contains("-")) {
            val split = periodStr.split(" - ")
            if (split.size > 1) {
                val startTime = split[0].trim()
                val endTime = split[1].trim()
                var startDate = ""
                var endDate = ""
                var effectTime = ""
                //正则按照空格拆分,\s+防止出先多个空格的情况
                val firstSplit = startTime.split("\\s+".toRegex())
                val secondSplit = endTime.split("\\s+".toRegex())

                if (firstSplit.isNotEmpty()) {
                    startDate = firstSplit[0]
                }
                if (secondSplit.isNotEmpty()) {
                    endDate = secondSplit[0]
                }
                if (firstSplit.size > 1 && secondSplit.size > 1) {
                    effectTime = "${firstSplit[1]} - ${secondSplit[1]}"
                }

                mBinding.keyStarttimeValue.text = startTime
                mBinding.keyEndtimeValue.text = endTime
                mBinding.keyStartdateValue.text = startDate
                mBinding.keyEnddateValue.text = endDate
                mBinding.keyEffectivetimeValue.text = effectTime

                if (repeatType == Base_DoorKeyRepeatType.NoRepeat.type) {
                    mBinding.rlStarttime.visibility = View.VISIBLE
                    mBinding.rlEndtime.visibility = View.VISIBLE
                } else {
                    mBinding.rlStartdate.visibility = View.VISIBLE
                    mBinding.rlEnddate.visibility = View.VISIBLE
                    mBinding.rlEffectivetime.visibility = View.VISIBLE
                }
            }
        }

    }

    override fun refreshDeleteStatus(data: StatusData) {
        if (data.flag) {
            setResult(Module_Secret_TempSecretFragment.RESULT_CODE)
            finish()
        }
        val message =
            if (data.flag) getString(R.string.secretkey_delete_success) else getString(R.string.secretkey_delete_failed)
        showToast(message)
    }

    override fun createPresenter(): Module_Secret_SecretKeyContract.Presenter = Module_Secret_SecretKeyPresenter()

    override fun initData() {
        val index = intent.getIntExtra("index", 0)
        secretKeyId = intent.getStringExtra("secretkey_id").toString()
        deviceMac = intent.getStringExtra("mac").toString()
    }

//    override fun attachLayoutRes(): Int = R.layout.activity_share_secretkey

    private lateinit var mBinding: ActivityShareSecretkeyBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityShareSecretkeyBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        rightIcon = findViewById(R.id.iv_title_bar_right)
        leftIcon = findViewById(R.id.image_title_bar_back)
        centerTitle = findViewById(R.id.tv_title_bar_center)
        leftTitle = findViewById(R.id.tv_title_bar_back)
        backLayout = findViewById(R.id.ll_title_bar_back)

        rightIcon?.run {
            setBackgroundResource(R.drawable.ic_delete)
            visibility = View.VISIBLE
            setOnClickListener(this@Module_Secret_SecretKeyDetailActivityNL)
        }

        centerTitle?.run {
            text = resources.getString(R.string.secretkey_detail_title)
        }

        leftTitle?.run {
            text = resources.getString(R.string.cancel_dialog_custom)
        }

        backLayout?.run {
            setOnClickListener(this@Module_Secret_SecretKeyDetailActivityNL)
        }

        mBinding.qrCode.setOnClickListener(this)
        mBinding.btnPreviewSave.setOnClickListener(this)
        mBinding.rlWechatShare.setOnClickListener(this)
        mBinding.rlEmailShare.setOnClickListener(this)
        mBinding.rlPictureShare.setOnClickListener(this)
        mBinding.rlPublicShare.setOnClickListener(this)
        loadData(true)
    }

    override fun initRestoreInstanceState(savedInstanceState: Bundle) {
        finish()
    }

//    private fun initTestData(){
//        val index = intent.getIntExtra("index", 0)
//        secretKeyId = intent.getIntExtra("secretkey_id", 0)
//        when (index % 2) {
//            0 -> loadData(true)
////            1 -> refreshQRCode("CIFI-A://YzYLLW7o3P6dAXq39IP1lkJVF3fWESKgxQZlfm5TIWE=")
//            1 -> loadData(false)
//        }
//    }

    private fun loadData(isValid: Boolean) {
//        mPresenter?.getQRInfo(isValid)
//        mPresenter?.getSecretKeyInfo(accessToken, secretKeyId)
        mPresenter?.getSecretKeyInfo(
            SecretKeyInfoRequest(
                accessToken,
                secretKeyId
            )
        )
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.ll_title_bar_back -> {
                if (isPreview) {
                    togglePreview()
                } else {
                    finish()
                }
            }

            R.id.rl_wechat_share -> showToast(
                resources.getString(
                    R.string.not_support_share,
                    resources.getString(R.string.share_wechat)
                )
            )

            R.id.rl_email_share -> showToast(
                resources.getString(
                    R.string.not_support_share,
                    resources.getString(R.string.share_email)
                )
            )

            R.id.rl_public_share -> {
                shareImage(Module_Secret_BitmapUtils.captureView(mBinding.content))
            }

            R.id.rl_picture_share -> {
                togglePreview()
            }

            R.id.btn_preview_save -> {
//                if (!PermissionHelper.required(this)
//                        .hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                ) {
//                    requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_SAVE_PICTURE_CODE)
//                    return
//                }
                savePictureToAlbum(Module_Secret_BitmapUtils.captureView(mBinding.content)!!)
            }

            R.id.qr_code -> {
                if (mBinding.qrCode.drawable !is BitmapDrawable) {
                    loadData(true)
                }
            }

            R.id.iv_title_bar_right -> {
                CustomDialog(this).setMessage(getString(R.string.secretkey_message_delete))
                    .setPositiveButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
//                            mPresenter?.deleteSecretKey(accessToken, arrayListOf(secretKeyId))
                            mPresenter?.deleteSecretKey(
                                SecretKeyDeleteRequest(
                                    accessToken,
                                    arrayListOf(secretKeyId)
                                )
                            )
                            dialog.dismiss()
                        }
                    }).setNegativeButton(object : CustomDialog.OnClickListener {
                        override fun onClick(dialog: CustomDialog) {
                            dialog.dismiss()
                        }
                    }).show()
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQUEST_SAVE_PICTURE_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                savePictureToAlbum(Module_Secret_BitmapUtils.captureView(mBinding.content)!!)
            } else {
                //拒绝
                showPermissionDialog()
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun showPermissionDialog() {
        val mDialog = DialogUtil.getConfirmDialog(
            this,
            getString(R.string.permission_content_storage),
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                }
            },
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {

                }
            }).show()
        mDialog.window?.run {
            attributes = attributes.apply {
                width = (windowManager.defaultDisplay.width * 0.95).toInt()
                gravity = Gravity.CENTER
            }
        }
    }


    private fun togglePreview() {
        isPreview = !isPreview
        if (isPreview) {
            mBinding.container.backgroundColor = ContextCompat.getColor(this, R.color.black)
            centerTitle?.text = resources.getString(R.string.share_picture_preview)
            mBinding.shareBottom.visibility = View.INVISIBLE
            leftIcon?.visibility = View.GONE
            leftTitle?.visibility = View.VISIBLE
            rightIcon?.visibility = View.GONE
            mBinding.contentBottom?.visibility = View.VISIBLE
            initColor(R.color.black)
        } else {
            mBinding.container.backgroundColor = ContextCompat.getColor(this, R.color.transparent)
            centerTitle?.text = resources.getString(R.string.secretkey_detail_title)
            mBinding.shareBottom.visibility = View.VISIBLE
            leftIcon?.visibility = View.VISIBLE
            leftTitle?.visibility = View.GONE
            rightIcon?.visibility = View.VISIBLE
            mBinding.contentBottom?.visibility = View.GONE
            initColor(R.color.transparent)
        }
    }

    //    override fun refreshQRCode(data: SecretQRCodeData) {
//        val qrMsg = data.value
//        qr_code.setImageBitmap(
//            QRCodeUtils.createQRCode(
//                qrMsg,
//                DensityUtil.dp2px(this, QR_IMAGE_SIZE)
//            )
//        )
//    }
//
    private fun refreshQRCode(data: String) {
        mBinding.qrCode.setImageBitmap(
            QRCodeUtils.createQRCode(
                data,
                Base_DensityUtil.dp2px(this, QR_IMAGE_SIZE)
            )
        )
    }

    private fun savePictureToAlbum(bitmap: Bitmap?) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val fileName = "${mBinding.keyNameValue.text}_" + formatCurrentTime()
                val contentValues = ContentValues()
                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
                contentValues.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis())
                val insertUri =
                    contentResolver.insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        contentValues
                    )
                val outputStream = contentResolver.openOutputStream(insertUri!!, "rw")
                if (bitmap != null) {
                    val quality = if (mBinding.cbImageQuality.isChecked) 100 else 50
                    if (bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream!!)) {
                        withContext(Dispatchers.Main) {
                            showToast(getString(R.string.save_picture_success))
                            sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, insertUri))
                            togglePreview()
                        }
                    } else {
                        //兼容某些型号手机无法保存到相册,储存至应用私有目录的Picture文件下
                        val folderName = "doorkey"
                        val fileName = "${mBinding.keyNameValue.text}_${formatCurrentTime()}.png"
                        val filePath = getFileStoragePath(folderName, fileName).absolutePath
                        val saveSuccess = Module_Secret_BitmapUtils.saveBitmapToFile(bitmap, filePath)
                        withContext(Dispatchers.Main) {
                            if (saveSuccess) {
                                showToast(getString(R.string.save_picture_success_inner, filePath))
                            } else {
                                showToast(getString(R.string.save_picture_failed))
                            }
                        }
                    }
                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
        }
    }

    fun getFileStoragePath(folderName: String, fileName: String): File {
        val path = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val folderPath = File("$path/$folderName")
        if (!folderPath.exists()) {
            folderPath.mkdir()
        }
        var file = File(folderPath, fileName)

        var prefix = 1
        while (file.exists()) {
            file = File(path, prefix.toString() + "_" + fileName)
            prefix += 1
        }
        return file
    }

    private fun shareImage(bitmap: Bitmap?) {
        MainScope().launch(Dispatchers.IO) {
            try {
                val file = File(cacheDir, "shareImage.jpg")
                val fos = FileOutputStream(file)
                bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.close()
                // 获取分享文件的URI
                val uri: Uri = FileProvider.getUriForFile(
                    this@Module_Secret_SecretKeyDetailActivityNL,
                    "$packageName.fileprovider",
                    file
                )
                // 创建分享意图
                val shareIntent = Intent(Intent.ACTION_SEND)
                shareIntent.type = "image/*"
                shareIntent.putExtra(Intent.EXTRA_STREAM, uri)

                // 添加权限
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                startActivity(Intent.createChooser(shareIntent, "Choose a sharing app"))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun formatCurrentTime(): String {
        return SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(Date())
    }
}